package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;
import com.ny.until.PasswordUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private EmailService emailService;
//    @Autowired
//    private PasswordUntil PasswordUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }
    @Override
    public User login(String username,String password){
        return userMapper.login(username,password);
    }

    @Override
    public int register(User user) {
        String Password = user.getPassword();
        String pwd = PasswordUntil.encryptPassword(Password);
        user.setPassword(pwd);
        return userMapper.register(user);
    }

    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }


    @Override
    public void sendEmailCode(String email) {
        //生成验证码
        String code = emailService.generateCode();
        // 把验证码存储到redis数据中,进行验证和过期的
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(email, code,10, TimeUnit.MINUTES);
        emailService.sendEmail(email, code);
    }

    @Override
    public int updatePasswordByEmail(String email, String password) {
        // 密码加密
        password = PasswordUntil.encryptPassword(password);
        redisTemplate.delete(email);//清楚redis的验证码
        return userMapper.updatePasswordByEmail(email, password);
    }
    @Override
    public boolean checkCode(String email, String code) {
        // 从redis中获取验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(email);
        if (redisCode != null && redisCode.equals(code)) {
            return true;
        }
        return false;
    }

//    @Resource
//    private UserMapper userMapper;

    // 实现用户查询逻辑（密码MD5加密后比对）
    @Override
    public User findUser(String username, String password) {
        return userMapper.findUser(username, PasswordUntil.md5(password));
    }

}
